package cn.itcast.controller;


import cn.itcast.domain.system.Module;
import cn.itcast.domain.system.User;
import cn.itcast.service.system.ModuleService;
import cn.itcast.service.system.UserService;
import org.apache.commons.lang.StringUtils;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;

@Controller
public class LoginController extends BaseController{  // 不建议继承 BaseController

    @Autowired
    private UserService userService;
    @Autowired
    private ModuleService moduleService;

    @Autowired
    private HttpSession session;
    @Autowired
    private HttpServletRequest request;

	@RequestMapping("/login")
	public String login(String email,String password,String openId) {
//	    判断邮箱或密码是否为空 ，如果为空了在登录页面上有一个友好的提示
        if(StringUtils.isEmpty(email)||StringUtils.isEmpty(password)){
            request.setAttribute("error","邮箱或密码不能为空");
            return "forward:/login.jsp";   //请求转发 保持使用的是同一个request
        }

//        开始shiro框架的认证（登录）方式
//        第一步：创建令牌 第二步：获取主题 第三步：开始认证
//        令牌中放入的密码是加密后的密码
        if (StringUtils.isEmpty(openId)) {
            password = new Md5Hash(password,email,2).toString();
        }
//        创建令牌
        UsernamePasswordToken token = new UsernamePasswordToken(email, password);
//        获取主题
        Subject subject = SecurityUtils.getSubject();
//        开始认证
        try {
            subject.login(token);
        } catch (AuthenticationException e) {
            request.setAttribute("error","邮箱或密码错误");
            return "forward:/login.jsp";   //请求转发 保持使用的是同一个request
        }

//        获取user 用到了shiro的会话管理
        User user = (User) subject.getPrincipal();


//       根据登录人查询菜单权限
        List<Module> moduleList = moduleService.findModuleListByUser(user);
        session.setAttribute("modules",moduleList);
//       表示登录成功 把当前登录人放到session中
        session.setAttribute("loginUser",user);
		return "home/main";
	}

    //退出
    @RequestMapping(value = "/logout",name="用户登出")
    public String logout(){
//        session.removeAttribute("loginUser");
        SecurityUtils.getSubject().logout();   //登出
        return "forward:login.jsp";
    }

    @RequestMapping("/home")
    public String home(){
	    return "home/home";
    }
    @RequestMapping("/weixin")
    public String getUrl(){
        return "redirect:https://open.weixin.qq.com/connect/qrconnect?appid=wx3bdb1192c22883f3&redirect_uri=http://note.java.itcast.cn/weixinlogin&response_type=code&scope=snsapi_login#wechat_redirect";
    }
    @RequestMapping("/rengzh")
    public String rengzh(String email,String password,String openId) {
        if (StringUtils.isEmpty(email) || StringUtils.isEmpty(password)) {
            request.setAttribute("error", "邮箱或密码不能为空");
            request.setAttribute("openId", openId);
            return "forward:/rengzh.jsp";
        }
        password = new Md5Hash(password, email, 2).toString();
        User user = userService.findByEmail(email);
        if (user != null) {
            String password_db = user.getPassword();
            if (!password.equals(password_db)) {
                request.setAttribute("error", "邮箱或密码错误");
                request.setAttribute("openId", openId);
                return "forward:/rengzh.jsp";
            }
        }
        user.setOpenId(openId);
        userService.update(user);
        request.setAttribute("user", user);
        return "forward:/weixinlgin.jsp";
    }
    @RequestMapping("/xiugai")
    public String xiugai(String yuan,String xin,String quereng) {
        if(StringUtils.isEmpty(yuan)||StringUtils.isEmpty(quereng)||StringUtils.isEmpty(quereng)){
            request.setAttribute("error","密码不可以为空");
            return "forward:/xiugai.jsp";
        }
        if (!xin.equals(quereng)){
            request.setAttribute("error","俩次密码不一致");
            return "forward:/xiugai.jsp";
        }
        User user = getUser();
        String password = new Md5Hash(yuan,user.getEmail(),2).toString();
        if (!password.equals(user.getPassword())){
            request.setAttribute("error","原密码错误");
            return "forward:/xiugai.jsp";
        }
        password = new Md5Hash(xin,user.getEmail(),2).toString();
        user.setPassword(password);
        userService.update(user);
        SecurityUtils.getSubject().logout();
        request.setAttribute("error","请重新登录");
	    return "forward:/login.jsp";
    }
}
